from fastapi import APIRouter, Depends

from . import models
from sqlalchemy.orm.session import Session
from ..dependencies import get_db
from .. import schemas
from ..crud import classes, users

router = APIRouter(
    prefix='/classes',
    tags=['班级操作']
)


@router.post('/create', response_model=models.class_return)
def create_class(Class: schemas.Classes_Create, db: Session = Depends(get_db)):
    return models.class_return(
        code=0,
        message='班级已创建',
        class_=classes.create_class(db, Class)
    )


@router.get('/get', response_model=models.classes_return)
def get_classes(limit: int = 10, offset: int = 0, db: Session = Depends(get_db)):
    Classes = classes.get_classes(db, limit, offset)
    if Classes == []:
        return models.classes_return(
            code=1,
            message='未找到班级',
            classes_=[]
        )
    return models.classes_return(
        code=0,
        message='已找到班级',
        classes_=Classes
    )


@router.post('/update', response_model=models.class_return)
def update_class(Class: schemas.Classes_Update, db: Session = Depends(get_db)):
    return models.class_return(
        code=0,
        message='班级信息已更新',
        class_=classes.update_classes(db, Class)
    )


# 连接班级用户
@router.post('/link_user', response_model=models.user_class_return)
# item是要输入的东西的结构
def link_user(item: schemas.User_Class_Create, db: Session = Depends(get_db),):
    # 获取用户以及班级
    user = users.get_user_by_number(db, item.number)
    _class = classes.get_class(db, item.class_name)
    # 判断是否启用（enable）
    if not user.enabled:
        return models.user_class_return(
            code=1,
            message='用户未启用',
            user_class=None
        )
    if not _class.enabled:
        return models.user_class_return(
            code=2,
            message='班级未启用',
            user_class=None
        )
    data = classes.get_user_class(db, user_id=user.id)
    if data and user.role == '学生':
        return models.user_class_return(
            code=3,
            message='已存在连接',
            user_class=data
        )
    return models.user_class_return(
        code=0,
        message='已创建连接',
        user_class=classes.create_user_class(
            db,
            user_id=user.id,
            classes_id=_class.id
        )
    )